package woaini.wind.bot.command.qylc.app.ticket.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONPath;
import org.springframework.stereotype.Service;
import woaini.wind.bot.command.qylc.app.ticket.api.QylcTicketApi;
import woaini.wind.bot.core.exception.BotAssertTool;
import woaini.wind.bot.core.exception.enums.BotExceptionType;

import java.util.ArrayList;
import java.util.List;

/**
 * @see QylcTicketService
 * @author yefeng {@date 2025-06-12 14:05:45}
 */
@Service
public class QylcTicketService {


  public List<String> getVoucherInfo(String cardNo) {
    String searchTicket = QylcTicketApi.searchTicket(cardNo);

    BotAssertTool.isActualTrue(
      StrUtil.isEmpty(searchTicket), BotExceptionType.BOT_SERVICE, "订单查询失败!!");

    //存在订单展示凭证信息
    String masterOrderNo =
      Convert.toStr(JSONPath.extract(searchTicket, "$.data.content[0].masterOrderNo"));

    String voucherInfo = QylcTicketApi.getVoucherInfo(masterOrderNo, cardNo);

    BotAssertTool.isActualTrue(
      StrUtil.isEmpty(voucherInfo), BotExceptionType.BOT_SERVICE, "凭证信息获取异常!!");
    String path = STR."$.data.vouches[?(@.vouchExtInfo=='\{cardNo}')][0]";

    JSONObject masterVoucher = (JSONObject) JSONPath.extract(voucherInfo, path);
    if (masterVoucher == null) {
        return new ArrayList<>(0);
    }
    String vouchCode = masterVoucher.getString("vouchCode");
    if (vouchCode.startsWith("SS")){
      return CollUtil.newArrayList(vouchCode);
    }else {
      //获取子凭证信息
      String subVoucherInfo = QylcTicketApi.getSubVoucherInfo(vouchCode);
      BotAssertTool.isActualTrue(
        StrUtil.isEmpty(subVoucherInfo), BotExceptionType.BOT_SERVICE, "子凭证信息获取异常!!");
     return (List<String>) JSONPath.extract(subVoucherInfo, "$.data.content[*].vouchCode");
    }
  }

}
